# coding: utf-8
# author: t_wolf

from commons import *


class REQUEST:
    """
    请求类: 无需实例化,用于请求中的参数定义及快速联想
    """

    def __init__(self):
        pass

    class Method:
        def __init__(self): pass

        method_list = ['get', 'post', 'put', 'delete']

    class DataType:
        def __init__(self): pass

        PARAM = 'param'
        XML = 'xml'
        JSON = 'json'

    DISPOSE_DATA = {
        DataType.XML: lambda: xml2params(web.data()),
        DataType.JSON: lambda: json2params(web.data()),
        DataType.PARAM: lambda: web.input()
    }


class RESPONSE:
    def __init__(self):
        pass

    class DataType:
        def __init__(self): pass

        PARAM = 'param'
        XML = 'xml'
        JSON = 'json'

    DISPOSE_DATA = {
        DataType.XML: lambda x: params2xml(x),
        DataType.JSON: lambda x: params2json(x),
        DataType.PARAM: lambda x: x,
    }


class SessionExpired(web.HTTPError):
    def __init__(self, headers, message):
        super(SessionExpired, self).__init__('200 OK', headers, data=message)


class FrSession(Session):
    def __init__(self, app, store, expired_page, initializer=None):
        super(FrSession, self).__init__(app, store, initializer)
        self.expired_page = expired_page

    def expired(self):
        self._killed = True
        self._save()
        # message = self._config.expired_message
        # headers = {'Content-Type': 'text/html','Redirect':'3;url="/"'}
        # raise session_expired(headers, message)
        raise web.seeother(self.expired_page, True)


class SESSION:
    def __init__(self, app):
        self.app = app
        web.config.session_parameters.update(
            CONFIGS.SESSION.options
        )

    def init(self):
        db = web.database(
            dbn="mysql",
            host=CONFIGS.DB.host,
            port=CONFIGS.DB.port,
            user=CONFIGS.DB.username,
            pw=CONFIGS.DB.password,
            db=CONFIGS.DB.database
        )
        return FrSession(
            self.app,
            web.session.DBStore(db, CONFIGS.DB.tables['session']),
            CONFIGS.PAGES.expired,
            initializer={'login': False}
        )

    @staticmethod
    def transfer(session):
        web.ctx.session = session

    @staticmethod
    def check_log():
        if not web.ctx.session.login:
            raise web.seeother(CONFIGS.PAGES.nolog, True)


class Header:
    def __init__(self):
        pass

    @staticmethod
    def add_header_redirect(url="", time=0):
        _urls = web.ctx.env.get('HTTP_REFERER', '/') if not len(url) else url
        _time = web.config.server_params['redirect_time'] if not time else time
        web.header('Content-Type', 'text/html')
        web.header('Refresh', '%d;url="%s"' % (_time, _urls))



def post_filter():
    pass


def format_data(data_type):
    pass
